package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryShopTypeToList() {
//        查询Redis缓存
        Long size = stringRedisTemplate.opsForList().size(RedisConstants.LIST_SHOP);
        List<String> shopTypeJSON=new ArrayList<>();
        List<ShopType> shopTypes =new ArrayList<>();
        if (size==null||size==0){
//            从数据库中查询
             shopTypes = getBaseMapper().selectList(null);
            if (shopTypes==null){
                return Result.fail("店铺类型列表为空");
            }
            for (ShopType shopType : shopTypes) {
                String typeJson = JSONUtil.toJsonStr(shopType);
                shopTypeJSON.add(typeJson);
            }
            stringRedisTemplate.opsForList().rightPushAll(RedisConstants.LIST_SHOP,shopTypeJSON);
            return Result.ok(shopTypes);

        }
//        查询到了结果
        shopTypeJSON = stringRedisTemplate.opsForList().range(RedisConstants.LIST_SHOP, 0, size - 1);
//        将JSON转换为商铺Type类型
        assert shopTypeJSON != null;
        for (String shopType : shopTypeJSON) {
            ShopType shopTypeBean = JSONUtil.toBean(shopType, ShopType.class, false);
            shopTypes.add(shopTypeBean);
        }
        return Result.ok(shopTypes);
    }
}
